package org.roger.index;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.spell.LevensteinDistance;
import org.apache.lucene.search.spell.PlainTextDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 创建拼写检查索引
 * 
 * @author luoweiyi
 */
public class SpellCheckerIndex {

	/**
	 * 生成检查索引
	 * 
	 * @param spellIndexPath
	 *            索引文件路径
	 * @param idcFilePath
	 *            原始字典文件路径
	 * @throws IOException
	 */
	public void createCheckerIndex(String spellIndexPath, String idcFilePath)
			throws IOException {
		Directory spellIndexDir = FSDirectory.open(new File(spellIndexPath));
		SpellChecker spellChecker = new SpellChecker(spellIndexDir);
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, null);
		// 生成检查索引词典
		spellChecker.indexDictionary(new PlainTextDictionary(new File(
				idcFilePath)), config, false);
		// close
		spellIndexDir.close();
		spellChecker.close();
	}

	/**
	 * 
	 * @param oriWord
	 *            输入的单词
	 * @param spellIndexPath
	 * 			       索引文件路径
	 * @throws IOException
	 */
	public void getSpellCheckerWord(String oriWord, String spellIndexPath)
			throws IOException {
		Directory spellIndexDir = FSDirectory.open(new File(spellIndexPath));
		SpellChecker spellChecker = new SpellChecker(spellIndexDir);
		spellChecker.setStringDistance(new LevensteinDistance());
		String[] words = spellChecker.suggestSimilar(oriWord, 5);
		for (String word : words) {
			System.out.println(word);
		}
	}

	public static void main(String[] args) {
		SpellCheckerIndex sci = new SpellCheckerIndex();
		// try {
		// sci.createCheckerIndex("D:/lucene/checkindex","D:/lucene/check/check.txt");
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		try {
			sci.getSpellCheckerWord("thr one", "D:/lucene/checkindex");
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}
}
